import pymongo, gridfs


from pylons import config, tmpl_context as c

class MongoDB():

    """
    Interface for MongoDB database
    """

    def __init__(self, collection = "results", series = "series"):
        """Initilize connection and check indeces"""

        try:
            # MongoDB URI
            uri = self.make_uri()

            # Database
            database = config["app_conf"]["mongo_db"]
            fs_database = config["app_conf"]["gridfs_db"]
            self.conn = pymongo.Connection(uri, safe=True)

            # Collection
            self.series = self.conn[database][series]
            self.collection = self.conn[database][collection]
            self.mh_collection = self.conn[database]["mh_" + collection] # multi-har-collection
            self.files_collection = self.conn[fs_database]["fs"]["files"]

            # gridfs
            self.fs = gridfs.GridFS(self.conn[fs_database])

            # Indecies
            self.ensure_index()

        except Exception as error:
            # Exception type: Exception message
            c.message = ": ".join([type(error).__name__, error.message])

    def make_uri(self):
        # Connection handler
        host = config["app_conf"]["mongo_host"]
        port = config["app_conf"]["mongo_port"]
        auth = config["app_conf"]["mongo_auth"]

        uri = "mongodb://"

        if auth == "true":
            user = config["app_conf"]["mongo_user"]
            pswd = config["app_conf"]["mongo_pswd"]
            uri += user + ":" + pswd + "@"

        return uri + host + ":" + port

    def ensure_index(self):
        self.collection.ensure_index([("timestamp", 1)])
        self.collection.ensure_index([("timestamp", -1)])
        self.collection.ensure_index([("series", 1), ("timestamp", -1)])
        self.collection.ensure_index([("series", 1), ("timestamp", 1)])

        self.mh_collection.ensure_index([("timestamp", 1)])
        self.mh_collection.ensure_index([("timestamp", -1)])
        self.mh_collection.ensure_index([("series", 1), ("timestamp", -1)])
        self.mh_collection.ensure_index([("series", 1), ("timestamp", 1)])

        self.files_collection.ensure_index([("uploadDate", 1)])
        self.files_collection.ensure_index([("uploadDate", -1)])

